<template>
  <el-dialog v-model="visible" :title="form.id ? '编辑用户' : '添加用户'" width="40%" @closed="closed">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" size="small">
      <el-form-item label="帐号：" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="姓名：" prop="nickName">
        <el-input v-model="form.nickName"></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item label="备注：">
        <el-input v-model="form.note" type="textarea" :rows="5"></el-input>
      </el-form-item>
      <el-form-item label="是否启用：">
        <el-radio-group v-model="form.status">
          <el-radio :value="1" border>是</el-radio>
          <el-radio :value="0" border>否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm" size="small">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import type { User } from '@/models/user'
import { ElMessage, type FormInstance } from 'element-plus'
import { createAdmin, updateAdmin, adminDetail } from '@/api/user'
defineOptions({ name: 'AdminUpsert' })
const emit = defineEmits(['refreshDataList'])
const rules = {
  username: [{ required: true, message: '帐号不能为空', trigger: 'blur' }],
  nickName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
}

const visible = ref(false)
const form = ref<User>({})
const formRef = ref<FormInstance>()

async function handleDialogConfirm() {
  await formRef.value?.validate()
  if (form.value.id) {
    await updateAdmin(form.value.id, form.value)
    ElMessage.success('修改成功！')
  } else {
    await createAdmin(form.value)
    ElMessage.success('添加成功！')
  }
  visible.value = false
  emit('refreshDataList')
}
const closed = () => {
  formRef.value?.resetFields()
}
const show = async (id?: number) => {
  visible.value = true
  if (id) {
    const res = await adminDetail(id)
    form.value = res.data.data
  } else {
    form.value = { status: 1 }
  }
}
defineExpose({ show })
</script>

<style scoped></style>
